#!/usr/bin/env python
# encoding: utf-8
# Author: colinspace.com
# Date: 2021-12
# Desc: heic/heif格式的照片转换成jpeg格式
#


import os
import sys
import pyheif
import whatimage
import traceback
from PIL import Image


def getFileAbsolutePath(resource_path):
    """
    遍历给定目录包括其子目录，获取所有文件路径
    """
    file_list = []
    if os.path.isdir(resource_path):
        for root, dirs, files in os.walk(resource_path):
            for file in files:
                file_path = os.path.join(root, file)
                file_list.append(file_path)
            for dir in dirs:
                if os.path.isfile(dir):
                    file_path = os.path.join(root, dir)
                    file_list.append(file_path)
        return file_list
    else:
        pass

def heifConvert2Jpeg(resource_path, dest_path):
    """
    转换给定的文件为jpg格式
    转换给定的目录下（包括子目录）下文件为Jpg格式
    结果写入指定的目录
    """
    if os.path.isdir(resource_path):
        for file in getFileAbsolutePath(resource_path):
            # 递归处理
            heifConvert2Jpeg(file, dest_path)
    elif os.path.isfile(resource_path):
        with open(resource_path, 'rb') as f:
            data = f.read()
            try:
                fmt = whatimage.identify_image(data)
                # 只处理 heic 格式进行转化
                if fmt in ['heic']:
                    heif_image = pyheif.read_heif(resource_path)
                    image = Image.frombytes(mode=heif_image.mode, size=heif_image.size, data=heif_image.data)
                    path, filename = os.path.split(resource_path)
                    name, ext = os.path.splitext(filename)
                    dest_filename = os.path.join(dest_path, "%s.jpg" % name)
                    print("%s convert to: %s" %(filename, dest_filename))
                    # 这里可以生成缩略图 thumbnail， 比如函数指定参数 thumbnail=False
                    # 默认不按缩略图生成
                    # if thumbnail:
                        # image.thumbnail((1080, 1440))
                        # image.save()
                    # else:
                    image.save(dest_filename, 'JPEG')
            except:
                traceback.print_exc()
    else:
        print("resource_path error! ")

def main():
    resource_path = "/tmp/temp-pyheif/"
    dest_path = "/tmp/convert_res"
    # 目标目录不存在的时候先创建
    if not os.path.exists(dest_path):
        os.makedirs(dest_path)
    heifConvert2Jpeg(resource_path, dest_path)

if __name__ == '__main__':
    main()